const fs = require('fs')
const Sina = require('./api/sina.js')
const Storage = require('./storage')
const { Notification } = require('electron')
const { resolve } = require('path')
const { start } = require('repl')

let Task = {
    RULES: [],
    CONFIG: {
        
    },
    TIMEER: null,
    storeHandler: null,

    turnOffRuleCheck() {
        this.CONFIG.status = 'off';
        this.getStoreHandler().updateConfig(this.CONFIG);
    },

    turnOnRuleCheck() {
        this.CONFIG.status = 'on';
        this.getStoreHandler().updateConfig(this.CONFIG);
    },

    init: function() {
        this.RULES = this.getStoreHandler().loadRules();
        this.CONFIG = this.getStoreHandler().loadConfig();

    },
    getStoreHandler() {
        if (!this.storeHandler) {
            this.storeHandler = new Storage();
        }
        return this.storeHandler;
    },

    generateByTemplate: function(template, ruleType, ruleValue, priceObj) {
        template = template.replace(new RegExp("{RULE_TYPE}",'g'), ruleType);
        template = template.replace(new RegExp("{RULE_VALUE}",'g'), ruleValue);
        template = template.replace(new RegExp("{CURRENT_PRICE}",'g'), priceObj.currentPrice);
        return template;
    },

    onNotification(singleShares, priceObj) {
        let _this = this
        let ruleType = singleShares.ruleType;
        let msg = '';
        let ruleTypeText = "";
        switch(ruleType) {
            case 'RDF':
                ruleTypeText = `跌幅>=`;
                break;
            case 'RZF':
                ruleTypeText = `涨幅>=`;
                break;
            case 'JGZ':
                ruleTypeText = `价格>=`;
                break;
            case 'JGD':
                ruleTypeText = `价格<=`;
                break;
            default:
                ruleTypeText = '';
                break;
        }

        msg = _this.generateByTemplate(_this.CONFIG.notificationTemplate, ruleTypeText, singleShares.ruleValue, priceObj);
        // 实例化不会进行通知
        let notification = new Notification({
            // 通知的标题, 将在通知窗口的顶部显示
            title: _this.CONFIG.hideNotifactionDetail ? '提示' : `${singleShares.ruleName}`,
            // 通知的副标题, 显示在标题下面 macOS
            subtitle: _this.CONFIG.hideNotifactionDetail ? '您收到一条新提示！！' :`${singleShares.sharesName}(${singleShares.sharesCode})`,
            // 通知的正文文本, 将显示在标题或副标题下面
            body: _this.CONFIG.hideNotifactionDetail ? '' : msg,
            // false有声音，true没声音
            silent: false,
            // 通知的超时持续时间 'default' or 'never'
            timeoutType: 'default',
        });
        
        // 向用户展示 notification
        notification.show()
    },

    run: function() {
        let _this = this
        // this.ruleChecked();
        this.TIMEER = setInterval(function () { 
           _this.ruleChecked();
        }, this.CONFIG.intervalMs);
    },

    ruleChecked: function () {
        let _this = this;
        if (_this.CONFIG.status === 'off') {
            return;
        }
        if (this.RULES.length > 0) {
            let items = [];
            for (let i=0; i<this.RULES.length; i++) {
                items.push(this.RULES[i]['sharesCode']);
            }
            Sina.search(items, (resObj) => {
                for (let ii=0; ii<this.RULES.length; ii++) {
                    let singleShares = this.RULES[ii];
                    if (resObj && resObj[singleShares.sharesCode]) {
                        let res = resObj[singleShares.sharesCode];
                        let ruleTypes = singleShares.ruleType;
                        let ruleValue = Number(singleShares.ruleValue);
                        let flag = false;

                        let currentPrice = Number(res.currentPrice);
                        let startPrice = Number(res.startPrice);
                        console.log(ruleTypes);
                        console.log(currentPrice <=startPrice);
                        if (currentPrice <= startPrice) {
                            if (ruleTypes == 'RDF' ) {
                                let percent = (startPrice - currentPrice)/startPrice * 100;
                                if (percent >= ruleValue) {
                                    flag = true;
                                }
                            }
                            if (ruleTypes == 'JGD') {
                                if (currentPrice <= ruleValue) {
                                    flag = true;
                                }
                            }
                        } else {
                            if (ruleTypes == 'RZF') {
                                let percent = (currentPrice - startPrice)/startPrice * 100;
                                console.log(percent);
                                console.log(percent >= ruleValue);
                                console.log(ruleValue);
                                console.log("*********")
                                if (percent >= ruleValue) {
                                    flag = true;
                                }
                            }
                            if (ruleTypes == 'JGZ') {
                                if (currentPrice >= ruleValue) {
                                    flag = true;
                                }
                            }
                        }
                        if (flag) {
                            _this.onNotification(singleShares, res);
                        }
                    }
                }
            });
        }
        
    },

    stop: function() {
        if (this.TIMEER) {
            clearInterval(this.TIMEER);
        }
    },

    reload: function() {
        this.init();
        this.stop();
        this.run();
    },

    setConfig: (newConfig) => {
        for (let key in CONFIG) {
            CONFIG[key] = newConfig[key];
        }
    },

    setRules: (newRules) => {
        this.stop();
        this.RULES = [];
        for (let i=0; i<newRules.length; i++) {
            this.RULES.push(JSON.parse(JSON.stringify(newRules[i])));
        }
        this.reload();
    }
}

module.exports = Task